package com.mall.shopping.services;

import com.alibaba.fastjson.JSON;
import com.mall.shopping.ICartService;
import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.services.cache.CartManager;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author ZhaoJiachen on 2021/5/22
 * <p>
 * Description: 购物车相关
 */

@Slf4j
@Component
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CartManager cartManager;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ProductConverter productConverter;


    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {

        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();

        try {
            // 获得 userId
            Long userId = request.getUserId();

            // 从redis中获取carts
            List<CartProductDto> carts = cartManager.getCarts(String.valueOf(userId));
            cartListByIdResponse.setCartProductDtos(carts);
            cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("CartServiceImpl.getCartListById occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(cartListByIdResponse, e);
        }

        return cartListByIdResponse;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            request.requestCheck();
            Example example = new Example(Item.class);
            example.createCriteria().andEqualTo("id", request.getProductId())
                    .andGreaterThanOrEqualTo("num", request.getProductNum())
                    .andGreaterThanOrEqualTo("limitNum", request.getProductNum());
            // 获取到CartProductDto
            List<Item> items = itemMapper.selectByExample(example);
            if (items == null || items.isEmpty()) {
                response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
                response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
                log.error("CartServiceImpl.addToCart occur Exception : " + ShoppingRetCode.DB_EXCEPTION.getMessage() +
                        "，商品库存不足或查找异常");
                return response;
            }
            Item item = items.get(0);
            CartProductDto cartProductDto = productConverter.item2CartProductDto(item);
            cartProductDto.setChecked("false");
            cartProductDto.setProductNum(Long.valueOf(request.getProductNum()));
            cartProductDto.setProductImg(cartProductDto.getProductImg().split(",")[0]);

            // 将此添加到redis
            boolean isAdd = cartManager.addToCart(request.getUserId(), request.getProductId(), cartProductDto);
            if (!isAdd) {
                response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
                response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
                log.error("CartServiceImpl.addToCart occur Exception : " + ShoppingRetCode.DB_EXCEPTION.getMessage());
                return response;
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            log.info("/shopping/carts 添加至购物车操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("CartServiceImpl.addToCart occur Exception : " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


    /**
     * http://localhost:9999/shopping/carts
     * Request Method: PUT
     * {"userId":"74","productId":100057601,"productNum":2,"checked":"true"}
     * @param request
     * @return
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        // 返回参数
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        // 获取map，更新map
        // 用户Id     userId
        Long userId = request.getUserId();

        //cart_userId  cart_74
        RMap<String,CartProductDto> map = redissonClient.getMap(GlobalConstants.CART_CACHE_PREFIX + String.valueOf(userId));
        String s = String.valueOf(request.getItemId());
        CartProductDto item = map.get(s);     //产品Id即productId
        try {
            if (item != null) {
                //TODO
                item.setProductNum(request.getNum().longValue());
                item.setChecked(request.getChecked());
//                CartProductDto cartProductDto = JSON.parseObject(item.toString(), CartProductDto.class);
//
//                cartProductDto.setChecked(request.getChecked())
//                              .setProductNum(request.getNum().longValue());

                //map.put(request.getItemId(), cartProductDto);
                map.put(s,item);
            }
        } catch (Exception e) {
            log.error("CartServiceImpl.updateCartNum Occur Exception : " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        // 返回
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        return null;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {

        Long userId = request.getUserId();
        Long itemId = request.getItemId();
        DeleteCartItemResponse response = new DeleteCartItemResponse();

        //todo: 删除购物车商品
        try {
            cartManager.deleteCartItem(String.valueOf(userId), String.valueOf(itemId));
                response.setCode(ShoppingRetCode.SUCCESS.getCode());
                response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("删除购物车商品发生错误"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne resposne = new DeleteCheckedItemResposne();
        try {
            Long userId = request.getUserId();
            cartManager.deleteCheckedItem(GlobalConstants.CART_CACHE_PREFIX +String.valueOf(userId));
        } catch (Exception e) {
            log.error("CartServiceImpl.deleteCheckedItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(resposne, e);
        }
        resposne.setCode(ShoppingRetCode.SUCCESS.getCode());
        resposne.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return resposne;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response=new ClearCartItemResponse();
        try{
            Long userId = request.getUserId();
            RMap<String,CartProductDto> itemMap = redissonClient.getMap(GlobalConstants.CART_CACHE_PREFIX + String.valueOf(userId));

            itemMap.values().forEach(obj -> {
                CartProductDto cartProductDto = JSON.parseObject(obj.toString(), CartProductDto.class);
                if(request.getProductIds().contains(cartProductDto.getProductId())){
                    itemMap.remove(cartProductDto.getProductId());
                }
            });
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("CartServiceImpl.clearCartItemByUserID Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
    private String generatorCartItemKey(Long userId){

        return GlobalConstants.CART_CACHE_PREFIX+String.valueOf(userId);
    }

}
